import { isFunction } from 'lodash'
import axios from 'axios'
import { generateRequestKey } from './helper'

let pendingMap = new Map()

export class AxiosCanceler {
  addPending (config) {
    this.removePending(config)
    const key = generateRequestKey(config)

    config.cancelToken =
      config.cancelToken ||
      new axios.CancelToken((cancel) => {
        if (!pendingMap.has(key)) {
          pendingMap.set(key, cancel)
        }
      })
  }

  removeAllPending () {
    pendingMap.forEach((cancel) => {
      cancel && isFunction(cancel) && cancel()
    })
    pendingMap.clear()
  }

  removePending (config) {
    const key = generateRequestKey(config)
    if (pendingMap.has(key)) {
      const cancel = pendingMap.get(key)
      cancel && cancel(key)
      pendingMap.delete(key)
    }
  }

  reset () {
    pendingMap = new Map()
  }
}
